'use client';

import React, { useEffect, useState, useContext } from 'react';
import { Table, Button, Space, Modal, Form, Input, InputNumber, Checkbox, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons';
import { serviceInfoApi } from '@/services/serviceInfoApi';
import { MessageApiContext } from '../layout/MainLayout';

const PAGE_SIZE = 20;

const ServiceInfo: React.FC = () => {
  const [data, setData] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editing, setEditing] = useState<any>(null);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const messageApi = useContext(MessageApiContext);

  // 获取服务信息列表
  const fetchData = async (pageNum = page) => {
    setLoading(true);
    try {
      const res = await serviceInfoApi.getServiceInfos({ page: pageNum, page_size: PAGE_SIZE });
      setData(res.data?.Data || []);
      setTotal(res.data?.TotalCount || 0);
    } catch {
      messageApi.error('获取服务信息失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData(1);
  }, []);

  const handleTableChange = (pagination: any) => {
    setPage(pagination.current);
    fetchData(pagination.current);
  };

  const showAddModal = () => {
    setEditing(null);
    setIsModalVisible(true);
  };

  const showEditModal = (record: any) => {
    setEditing(record);
    setIsModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      const res = await serviceInfoApi.deleteServiceInfo(id);
      messageApi.success(res?.message || '删除成功');
      fetchData(page);
    } catch (err: any) {
      messageApi.error(err?.response?.data?.message || err?.message || '删除失败');
    }
  };

  const handleBatchDelete = async () => {
    try {
      const results = await Promise.all(selectedRowKeys.map(id => serviceInfoApi.deleteServiceInfo(Number(id))));
      setSelectedRowKeys([]);
      // 展示所有message
      results.forEach(res => messageApi.success(res?.message || '删除成功'));
      fetchData(page);
    } catch (err: any) {
      messageApi.error(err?.response?.data?.message || err?.message || '批量删除失败');
    }
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      values.port = Number(values.port); // 保证port为数字
      let res;
      if (editing) {
        res = await serviceInfoApi.updateServiceInfo(editing.ID, values);
      } else {
        res = await serviceInfoApi.createServiceInfo(values);
      }
      if (res?.code === 0) {
        messageApi.success(res?.message || '操作成功');
      } else {
        messageApi.error(res?.message || '操作失败');
        return;
      }
      setIsModalVisible(false);
      fetchData(page);
    } catch (err: any) {
      // 校验或接口错误
      messageApi.error(err?.response?.data?.message || err?.message || '操作失败');
    }
  };

  useEffect(() => {
    if (isModalVisible && editing) {
      setTimeout(() => {
        form.setFieldsValue({
          port: editing.Port,
          service: editing.Service,
        });
      }, 2);
    }
    if (isModalVisible && !editing) {
      setTimeout(() => {
        form.resetFields();
      }, 2);
    }
  }, [isModalVisible, editing, form]);

  const columns = [
    {
      title: <Checkbox
        checked={selectedRowKeys.length === data.length && data.length > 0}
        indeterminate={selectedRowKeys.length > 0 && selectedRowKeys.length < data.length}
        onChange={e => setSelectedRowKeys(e.target.checked ? data.map(item => item.ID) : [])}
      />,
      dataIndex: 'select',
      render: (_: any, record: any) => (
        <Checkbox
          checked={selectedRowKeys.includes(record.ID)}
          onChange={e => {
            const newSelected = e.target.checked
              ? [...selectedRowKeys, record.ID]
              : selectedRowKeys.filter(key => key !== record.ID);
            setSelectedRowKeys(newSelected);
          }}
        />
      ),
      width: 48,
    },
    { title: '编号', dataIndex: 'ID', key: 'ID', width: 80 },
    { title: '端口', dataIndex: 'Port', key: 'Port', width: 100 },
    { title: '服务', dataIndex: 'Service', key: 'Service', width: 120 },
    { title: '创建时间', dataIndex: 'CreateTime', key: 'CreateTime', width: 180, render: (t: string) => new Date(t).toLocaleString() },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space>
          <Button icon={<EditOutlined />} size="small" onClick={() => showEditModal(record)}>编辑</Button>
          <Popconfirm title="确定删除吗?" onConfirm={() => handleDelete(record.ID)}>
            <Button icon={<DeleteOutlined />} size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
      width: 140,
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={showAddModal}>新增</Button>
          <Popconfirm title="确定批量删除所选服务吗?" onConfirm={handleBatchDelete} disabled={selectedRowKeys.length === 0}>
            <Button icon={<DeleteOutlined />} danger disabled={selectedRowKeys.length === 0}>批量删除</Button>
          </Popconfirm>
        </Space>
        <Button
          type="text"
          icon={<ReloadOutlined />}
          onClick={() => fetchData(page)}
          loading={loading}
          aria-label="刷新"
        />
      </div>
      <Table
        rowKey="ID"
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={{ current: page, pageSize: PAGE_SIZE, total, showSizeChanger: false }}
        scroll={{ x: 800 }}
        onChange={handleTableChange}
      />
      <Modal
        title={editing ? '编辑服务' : '新增服务'}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={() => setIsModalVisible(false)}
        destroyOnHidden
      >
        <Form form={form} layout="vertical" preserve={false}>
          <Form.Item name="port" label="端口" rules={[{ required: true, message: '请输入端口号' }]}>
             <InputNumber min={1} max={65535-3}  style={{ width: '100%' }}/> 
          </Form.Item>
          <Form.Item name="service" label="服务" rules={[{ required: true, message: '请输入服务名' }]}> 
            <Input /> 
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

(ServiceInfo as any).title = '服务信息';
export default ServiceInfo; 